package com.example.glgk.service.gather;

import com.example.glgk.dto.*;
import com.example.glgk.dto.gather.DeptOrderDto;
import com.example.glgk.entity.DepartmentIndicatorEntity;
import com.example.glgk.entity.ElementDataEntity;
import com.example.glgk.entity.IndicatorDataEntity;
import com.example.glgk.mapper.*;
import com.example.glgk.utils.CalculatorUtils;
import com.example.glgk.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lxk
 */
@Service
@Slf4j
public class GatherCommonService {

    @Autowired
    DepCPMapper depCPMapper;

    @Autowired
    IndicatorDataMapper indicatorDataMapper;

    @Autowired
    ElementDataMapper elementDataMapper;

    @Autowired
    ElementDataDayMapper elementDataDayMapper;

    @Autowired
    ElementDataMonthMapper elementDataMonthMapper;

    @Autowired
    ClinicalGatherService clinicalGatherService;



    //新增一个科室指标数据表格——>新增页面:第一列科室名称，后面的列，动态列展示的是大指标
    public List<EscalationDeptData> queryDeptData(QueryEscalation queryEscalation) {
        queryEscalation.setAllTimes(queryEscalation.getTimes());
        //先不做分页看看
        List<EscalationDeptData> result =new ArrayList<>();
        List<String> deptNames = queryEscalation.getDeptNames();
        if(CollectionUtils.isEmpty(deptNames)){
            return null;
        }

        //查询科室层面的大指标数据（不带分子分母）
        List<IndicatorDataEntity> list = indicatorDataMapper.queryMajorIndicator(queryEscalation);
        List<String> elementIds = getAllElementIds(list);
        //查询元素定义表，确定元素数据来源
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        Map<String, Map<String, List<DepartmentIndicatorEntity>>> dayMap = getData(elementDataEntities, "1", queryEscalation); //天表数据
        Map<String, Map<String, List<DepartmentIndicatorEntity>>> monthMap = getData(elementDataEntities, "2", queryEscalation); //月表数据
        Map<String, Map<String, List<DepartmentIndicatorEntity>>> handMap = getData(elementDataEntities, "3", queryEscalation); //填报表数据
        if(!CollectionUtils.isEmpty(deptNames)){
            for (int i = 0; i < deptNames.size(); i++) {
                String deptName = deptNames.get(i);
                EscalationDeptData escalationData = new EscalationDeptData();
                escalationData.setProject(deptName);
                escalationData.setRow(i + 1);
                for (IndicatorDataEntity entity : list) {
                    //计算公式
                    String calculationFormulaId = entity.getCalculationFormulaId();
                    log.info("指标{}的计算公式为:{}",entity.getIndexName(),calculationFormulaId);
                    if (StringUtils.isBlank(entity.getIds())) {
                        escalationData.getDynamicColumns().put(entity.getIndexName(), "-");
                        continue;
                    }
                    List<DepartmentIndicatorEntity> elementDays = new ArrayList<>();
                    String[] ids = entity.getIds().split(",");
                    for (String id : ids) {
                        if (!CollectionUtils.isEmpty(dayMap.get(deptName)) && !CollectionUtils.isEmpty(dayMap.get(deptName).get(id))) {
                            List<DepartmentIndicatorEntity> mapValues = dayMap.get(deptName).get(id);
                            elementDays.addAll(mapValues);
                        } else if (!CollectionUtils.isEmpty(monthMap.get(deptName)) && !CollectionUtils.isEmpty(monthMap.get(deptName).get(id))) {
                            List<DepartmentIndicatorEntity> mapValues = monthMap.get(deptName).get(id);
                            elementDays.addAll(mapValues);
                        }else if (!CollectionUtils.isEmpty(handMap.get(deptName)) && !CollectionUtils.isEmpty(handMap.get(deptName).get(id))){
                            List<DepartmentIndicatorEntity> mapValues = handMap.get(deptName).get(id);
                            elementDays.addAll(mapValues);
                        }
                    }
                    log.info("指标{}的元素数据为:{}",entity.getIndexName(),elementDays);
                    CalculatorUtils.calculator(elementDays, entity, calculationFormulaId, escalationData);
                }
                result.add(escalationData);
            }
        }
        return result;

    }

    public void export(QueryEscalation queryEscalation, HttpServletResponse response) {
        List<EscalationDeptData> escalationDeptData = queryDeptData(queryEscalation);
        ExcelUtils.exportExcel(response, escalationDeptData, EscalationDeptData.class, queryEscalation);
    }

    public void exportGatherClinicalData(QueryEscalation queryEscalation, HttpServletResponse response) {
        List<EscalationDeptData> escalationDeptData = clinicalGatherService.queryGatherClinicalIndicatorData(queryEscalation);
        ExcelUtils.exportExcel(response, escalationDeptData, EscalationDeptData.class, queryEscalation);
    }

    /**
     * 查询科室下拉列表
     * @return
     */
    public Map<String,List<String>> queryDeptNames() {
        List<DeptOrderDto> deptOrderDtos = depCPMapper.queryBA();
        return deptOrderDtos.stream()
                .collect(Collectors.groupingBy(DeptOrderDto::getGroupName,
                        Collectors.mapping(DeptOrderDto::getName, Collectors.toList())));
    }

    /**
     * 查询指标（元素）在总的元素ids
     *
     * @param list
     * @return
     */
    public List<String> getAllElementIds(List<IndicatorDataEntity> list) {
        if (org.springframework.util.CollectionUtils.isEmpty(list)) {
            return null;
        }
        //把list里面的ids全部单拎出来，去重，然后查询把所有的元素id查出来 但是还是要分月表，天表，手填表 所以数据源list应该分类，暂时只考虑天表，月表
        List<String> elementIds = new ArrayList<>();
        for (IndicatorDataEntity indicatorDataEntity : list) {
            if (StringUtils.isNotBlank(indicatorDataEntity.getIds())) {
                String[] split = indicatorDataEntity.getIds().split(",");
                elementIds.addAll(Arrays.asList(split));
            }
        }
        if (elementIds.isEmpty()) {
            return null;
        }
        elementIds = elementIds.stream().distinct().collect(Collectors.toList());
        return elementIds;
    }

    /**
     * 获取对应来源的元素数据
     * @param elementDataEntities
     * @param dataTable 1 元素天表 2元素月表 3填报表
     * @param queryEscalation
     * @return
     */
    public Map<String, Map<String, List<DepartmentIndicatorEntity>>> getData(List<ElementDataEntity> elementDataEntities, String dataTable,QueryEscalation queryEscalation) {
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> tableData = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && dataTable.equals(s.getDataTable())).collect(Collectors.toList());
        List<DepartmentIndicatorEntity> data = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tableData)) {
            queryEscalation.setElementIds(tableData.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            if ("1".equals(dataTable)){
                log.info("查询实际数据的元素id为:{}",queryEscalation.getElementIds());
                data = elementDataDayMapper.queryEscalationDept(queryEscalation); //天表数据
            }else if("2".equals(dataTable)){
                if(queryEscalation.getTimes().get(0).length() != 10){
                    data = elementDataMonthMapper.queryEscalationDept(queryEscalation); //月表数据
                }
            }
        }
        //将数据的deptName做成最外层的key，id做成内层的key Map<String,Map<String, List<DepartmentIndicatorEntity>>>
        return data.stream().filter(s->null != s.getDeptName() && null != s.getId())
                .collect(Collectors.groupingBy(DepartmentIndicatorEntity::getDeptName,
                        Collectors.groupingBy(DepartmentIndicatorEntity::getId)));
    }

    /**
     * 处理导出数据
     *
     * @param escalationData
     */
    public void dataProcess(List<EscalationData> escalationData) {
        escalationData = escalationData.stream().filter(s -> StringUtils.isNotBlank(s.getUnit())).collect(Collectors.toList());
        for (EscalationData data : escalationData) {
            for (String key : data.getDynamicColumns().keySet()) {
                String value = data.getDynamicColumns().get(key);
                if (!"-".equals(data.getDynamicColumns().get(key))) {
                    if (data.getUnit().contains("%")) {
                        value = new BigDecimal(value).multiply(new BigDecimal(100)).setScale(4, RoundingMode.HALF_UP) + "%";
                    } else {
                        value = new BigDecimal(value).setScale(4, RoundingMode.HALF_UP) + "";
                    }
                    data.getDynamicColumns().put(key, value);
                }
            }
        }
    }


    /**
     * 查询大指标下拉列表
     * @param userInfo
     * @return
     */
    public List<DropDownDto> queryIndicators(UserInfo userInfo) {
        return indicatorDataMapper.queryIndicator(userInfo);
    }


    /**
     * 查询部门下拉列表
     * @return
     */
    public Set<String> queryDeptName() {
        List<String> deptNames = indicatorDataMapper.queryDeptName();
        //把deptNames里不包含,的加入新的集合，如果包含,的切割之后再加入新的集合
        Set<String> newDeptsSet = new HashSet<>();
        for (String deptName : deptNames) {
            if (deptName.contains(",")) {
                // 包含逗号时，切割并添加到集合中
                String[] subDeptNames = deptName.split(",");
                newDeptsSet.addAll(Arrays.asList(subDeptNames));
            } else {
                // 不包含逗号时直接添加到集合中
                newDeptsSet.add(deptName);
            }
        }
        return newDeptsSet;
    }


}
